let app = getApp();
let location = require("../../../mybehaviors/location/location");
import Dialog from '../../../dist/dialog/dialog';
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    orderShow:false, //开启优惠券弹窗
    imageRight:true,
    orderId:null,
    goodsId:null,
    refundId: null, //售后ID
    addressDetail:'',
    storeName:'', //商户名称
    couponStore: {}, //券码信息
    couponList: [], //券码列表
    usableCoupon: [],
    couponCode: '',
    latitude:'',
    longitude: '',
    details: {},
    storeListByGoods: [], //商户列表信息
    orderType: 'shop',
    evaluateType:0,
    succees:0,
    //客服插件
    showService: false,
    customerOpen: false,
    cservice:'',
    serviceQRcode:'',
    serviceMobile:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if((options.orderId??'') !== '') {
      this.setData({
        orderId: Number(options.orderId)
      })
    }
    try {
      wx.removeStorageSync('applyaddresspoint');
    } catch (e) {
      // Do something when catch error
    }
    this._getLocation((mapdata, e) => {
      this.setData({
        longitude: e.lng,
        latitude: e.lat,
      });
      this.storeorderDetails();
    });
    this.orderCoupon();
    
    
   
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try {
      let value = wx.getStorageSync('applyaddresspoint');
      console.log(value);
      if (value) {
        console.log(value);
        this.setData({
          longitude: e.lng,
          latitude: e.lat,
        });
        console.log(this.data.longitude);
        // Do something with return value
      }
    } catch (e) {
      console.log(e);
    }
  },
  // 获取客服
  service() {
    let urlStr = app.getNetAddresss("goods.customer-service.index");
    app._postNetWork({
      url: urlStr,
      data: {
        goods_id: this.data.goodsId,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            customerOpen:res.data.customer_open,
            cservice: res.data.cservice,
            serviceQRcode: res.data.service_QRcode,
            serviceMobile: res.data.service_mobile,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  orderCoupon() {  //消费券二维码
    wx.showLoading({
      title: '加载中',
    });
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.order.orderCoupon");
    let json = {
      order_id:this.data.orderId,
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        let couponList = res.data;
        let couponCode = '';
        let usableCoupon = [];
        couponCode = couponList.find(item =>  item.status === 0);
        usableCoupon = couponList.filter((item) =>  item.status === 0);
        if (res.result == 1) {
          wx.hideLoading();
          this.setData({
            couponList: res.data,
            couponCode,
            usableCoupon
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  copyCode(event) {
    let text = event.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          //这个api是把拿到的数据放到电脑系统中的
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            });
          }
        })
      }
      })
  },
  getStoreListByGoods() {
    let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.store.getStoreListByGoods");
    let json = {
      goods_id:this.data.goodsId,
      longitude: this.data.longitude,
      latitude: this.data.latitude,
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        let storeaddress = resdata.data.data?.data;
        let addressDetail = `${storeaddress[0].city}${storeaddress[0].district}${storeaddress[0].street}${storeaddress[0].address}`;
        if (res.result == 1) {
          this.setData({
            addressDetail,
            storeListByGoods: res.data.data
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  orderstateOn(event) { //后端传的按钮api点击事件
    const e = event.currentTarget.dataset,
          id = e.id,
          value = e.value,
          api = e.api;
    if(value === 9) {
      Dialog.confirm({
        title: '提示',
        message: '确定取消该订单?',
      }).then(() => {
        // on close
        this.cancelPay(id,api);
      })
      .catch(() => {
        // on cancel
      });
    }
    if(value === 1) {
      wx.navigateTo({
        url: '/packageD/buy/orderPay/orderPay?order_id=' + id + '&status=2'
      });
    }
  },
  cancelPay(id,api) {
    let urlStr = app.getNetAddresss(api);
    let json = {
      order_id:id
    };
    app._postNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.storeorderDetails();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  refreshCode() { //刷新扫码的二维码信息
    this.orderCoupon();
  },
  navigationLocation() {
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=storeApply'
    });
  },
  shopNavTo() {
    wx.navigateTo({
      url: `/packageF/consumption/shopList/shopList?goodsId=${this.data.goodsId}&longitude=${this.data.longitude}&latitude=${this.data.latitude}`
    })
  },
  onClose() {
    this.setData({
      orderShow: !this.data.orderShow
    });
  },
  onQrcode() {
    this.setData({
      orderShow: true
    });
  },
  storeorderDetails() {
    let urlStr = app.getNetAddresss("order.detail");
    let json = {
      order_id:this.data.orderId,
      basic_info: 1
    };
    app._getNetWork({
      url: urlStr,
      data:json,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          console.log(res.data.has_many_order_goods[0]?.goods_id);
          this.setData({
            couponStore: res.data.coupon_store,
            details: res.data,
            goodsId: res.data.has_many_order_goods[0]?.goods_id,
            refundId: res.data.refund_id,
            storeName: res.data.coupon_store.coupon_list[0]?.has_one_store?.store_name,
            pluginSetting: res.basic_info?.plugin_setting?.coupon_store
          })
          this.getStoreListByGoods(); //商品可用商户列表
          this.service(); //客服插件
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  evaluateBtn(event) {
    let storeName = event.currentTarget.dataset.sotrename;
    wx.navigateTo({
      url: `/packageF/consumption/evaluate/evaluate?orderId=${this.data.orderId}&type=1&storeName=${storeName}`,
    })
  },
  refundBtn() {
    wx.navigateTo({
      url: `/packageF/consumption/refundOrder/refundOrder?orderId=${this.data.orderId}&type=2&orderType=1`,
    })
  },
  afterSaleBtn() {
    wx.navigateTo({
      url: `/packageF/consumption/refundProcess/refundProcess?refundId=${this.data.refundId}`
    });
  },
  showPop() {
    console.log('12342');
    let setServicePlugin = app._isTextEmpty(this.data.serviceQRcode) && app._isTextEmpty(this.data.serviceMobile);
    if (app._isTextEmpty(this.data.cservice) && setServicePlugin) {
      return app.tips("抱歉，暂未设置客服信息");
    }
    if (!app._isTextEmpty(this.data.cservice) && setServicePlugin) {
      this.gotoChat({
        currentTarget: {
          dataset: {
            cservice: this.data.cservice
          }
        }
      }) //只设置了客服链接，直接跳转
      return;
    }
    this.setData({
      serviceShow: true,
    });
  },
  closePop() {
    this.setData({
      serviceShow: false,
    });
  },
  gotoChat(evt) { //客服跳转
    console.log(evt);
    let url = evt.currentTarget.dataset.cservice + "&goods_id=" + this.data.goodsId;
    wx.navigateTo({
      url: url,
      fail: (err) => {
        app.tips("客服路由出错");
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})